<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻管理后台</title>
    <!-- Quill编辑器样式 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.7/quill.snow.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .dashboard {
            display: grid;
            grid-template-columns: 280px 1fr;
            min-height: 100vh;
        }

        .sidebar {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            padding: 2rem;
            border-right: 1px solid rgba(255, 255, 255, 0.2);
        }

        .sidebar h1 {
            color: #2d3748;
            margin-bottom: 2rem;
            font-size: 1.5rem;
            text-align: center;
        }

        .nav-menu {
            list-style: none;
        }

        .nav-item {
            margin-bottom: 0.5rem;
        }

        .nav-link {
            display: block;
            padding: 0.75rem 1rem;
            color: #4a5568;
            text-decoration: none;
            border-radius: 8px;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .nav-link:hover, .nav-link.active {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            transform: translateX(5px);
        }

        .main-content {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            padding: 2rem;
            overflow-y: auto;
        }

        .content-section {
            display: none;
            animation: fadeIn 0.5s ease;
        }

        .content-section.active {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 2rem;
            margin-bottom: 2rem;
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }

        .card h2 {
            color: #2d3748;
            margin-bottom: 1.5rem;
            font-size: 1.5rem;
        }

        .btn {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            margin-right: 1rem;
            margin-bottom: 1rem;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #718096, #4a5568);
        }

        .btn-danger {
            background: linear-gradient(135deg, #f56565, #e53e3e);
        }

        .btn-success {
            background: linear-gradient(135deg, #48bb78, #38a169);
        }

        .btn-warning {
            background: linear-gradient(135deg, #ed8936, #dd6b20);
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #2d3748;
            font-weight: 500;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            font-size: 1rem;
            background: rgba(255, 255, 255, 0.9);
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        textarea.form-control {
            min-height: 120px;
            resize: vertical;
        }

        /* 编辑器容器样式 */
        .editor-container {
            background: white;
            border-radius: 8px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            transition: border-color 0.3s ease;
        }

        .editor-container:focus-within {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        /* Quill编辑器自定义样式 */
        .ql-editor {
            min-height: 300px;
            font-size: 14px;
            line-height: 1.6;
        }

        .ql-toolbar {
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            border-radius: 8px 8px 0 0;
        }

        .ql-container {
            border-radius: 0 0 8px 8px;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        .table th, .table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .table th {
            background: rgba(102, 126, 234, 0.1);
            color: #2d3748;
            font-weight: 600;
        }

        .table tr:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .status-published {
            background: #c6f6d5;
            color: #22543d;
        }

        .status-draft {
            background: #fed7d7;
            color: #742a2a;
        }

        .tag {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            background: rgba(102, 126, 234, 0.2);
            color: #667eea;
            border-radius: 20px;
            font-size: 0.8rem;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
        }

        .tag-selectable {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            background: rgba(102, 126, 234, 0.1);
            color: #667eea;
            border-radius: 20px;
            font-size: 0.8rem;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1px solid transparent;
        }

        .tag-selectable:hover {
            background: rgba(102, 126, 234, 0.2);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }

        .tag-selectable.selected {
            background: rgba(102, 126, 234, 0.3);
            border-color: #667eea;
            font-weight: 500;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            animation: fadeIn 0.3s ease;
        }

        .modal-content {
            background: white;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 16px;
            width: 90%;
            max-width: 900px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .close {
            float: right;
            font-size: 1.5rem;
            cursor: pointer;
            color: #718096;
        }

        .close:hover {
            color: #2d3748;
        }

        .weight-controls {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
            margin-top: 1rem;
        }

        .weight-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            background: rgba(102, 126, 234, 0.1);
            border-radius: 8px;
        }

        .search-box {
            position: relative;
            margin-bottom: 1rem;
        }

        .search-box input {
            padding-left: 2.5rem;
        }

        .search-icon {
            position: absolute;
            left: 0.75rem;
            top: 50%;
            transform: translateY(-50%);
            color: #718096;
        }

        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            border: 1px solid transparent;
        }

        .alert-success {
            background: #c6f6d5;
            border-color: #9ae6b4;
            color: #22543d;
        }

        .alert-error {
            background: #fed7d7;
            border-color: #feb2b2;
            color: #742a2a;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .pagination {
            display: flex;
            justify-content: center;
            gap: 0.5rem;
            margin-top: 2rem;
        }

        .pagination button {
            padding: 0.5rem 1rem;
            border: 1px solid rgba(255, 255, 255, 0.3);
            background: rgba(255, 255, 255, 0.9);
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .pagination button:hover, .pagination button.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.9);
            padding: 1.5rem;
            border-radius: 12px;
            text-align: center;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 600;
            color: #667eea;
            margin-bottom: 0.5rem;
        }

        .stat-label {
            color: #4a5568;
            font-size: 0.9rem;
        }

        .view-count-display {
            color: #e74c3c;
            font-weight: 500;
        }

        /* 编辑器工具栏按钮样式优化 */
        .editor-toolbar-btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.8rem;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
            transition: all 0.3s ease;
        }

        .editor-toolbar-btn:hover {
            background: #5a67d8;
            transform: translateY(-1px);
        }

        @media (max-width: 768px) {
            .dashboard {
                grid-template-columns: 1fr;
            }

            .sidebar {
                display: none;
            }

            .main-content {
                padding: 1rem;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .modal-content {
                width: 95%;
                margin: 2% auto;
                padding: 1rem;
            }
        }
    </style>
</head>
<body>
<div class="dashboard">
    <div class="sidebar">
        <h1>📰 新闻管理</h1>
        <ul class="nav-menu">
            <li class="nav-item">
                <a class="nav-link active" onclick="showSection('dashboard')">📊 数据概览</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" onclick="showSection('articles')">📝 文章管理</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" onclick="showSection('categories')">📁 分类管理</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" onclick="showSection('tags')">🏷️ 标签管理</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" onclick="showSection('viewStats')">📈 浏览统计</a>
            </li>
        </ul>
    </div>

    <div class="main-content">
        <!-- 数据概览 -->
        <div id="dashboard" class="content-section active">
            <div class="card">
                <h2>数据概览</h2>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-number" id="totalArticles">0</div>
                        <div class="stat-label">文章总数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="publishedArticles">0</div>
                        <div class="stat-label">已发布文章</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalViews">0</div>
                        <div class="stat-label">总浏览量</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalCategories">0</div>
                        <div class="stat-label">分类数量</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalTags">0</div>
                        <div class="stat-label">标签数量</div>
                    </div>
                </div>
                <div style="text-align: center; margin-top: 2rem;">
                    <button class="btn" onclick="refreshStats()">🔄 刷新统计</button>
                    <button class="btn btn-warning" onclick="flushViewCount()">💾 刷新浏览量缓存</button>
                </div>
            </div>
        </div>

        <!-- 文章管理 -->
        <div id="articles" class="content-section">
            <div class="card">
                <h2>文章管理</h2>
                <div class="search-box">
                    <span class="search-icon">🔍</span>
                    <input type="text" id="searchKeyword" class="form-control" placeholder="搜索文章标题、作者或内容..." onkeyup="searchArticles()">
                </div>
                <div style="margin-bottom: 1rem;">
                    <select id="categoryFilter" class="form-control" style="width: 200px; display: inline-block; margin-right: 1rem;" onchange="filterArticles()">
                        <option value="">全部分类</option>
                    </select>
                    <select id="statusFilter" class="form-control" style="width: 150px; display: inline-block; margin-right: 1rem;" onchange="filterArticles()">
                        <option value="">全部状态</option>
                        <option value="1">已发布</option>
                        <option value="0">草稿</option>
                    </select>
                    <button class="btn" onclick="showCreateArticleModal()">➕ 新增文章</button>
                    <button class="btn btn-warning" onclick="refreshArticleViews()">📊 刷新浏览量</button>
                </div>
                <div id="articlesList">
                    <div class="loading"></div>
                </div>
            </div>
        </div>

        <!-- 分类管理 -->
        <div id="categories" class="content-section">
            <div class="card">
                <h2>分类管理</h2>
                <button class="btn" onclick="showCreateCategoryModal()">➕ 新增分类</button>
                <button class="btn btn-danger" onclick="clearOldNews()" style="float: right;">🗑️ 清理旧新闻</button>
                <div id="categoriesList">
                    <div class="loading"></div>
                </div>
            </div>
        </div>

        <!-- 标签管理 -->
        <div id="tags" class="content-section">
            <div class="card">
                <h2>标签管理</h2>
                <button class="btn" onclick="showCreateTagModal()">➕ 新增标签</button>
                <div id="tagsList">
                    <div class="loading"></div>
                </div>
            </div>
        </div>

        <!-- 浏览统计 -->
        <div id="viewStats" class="content-section">
            <div class="card">
                <h2>浏览统计</h2>
                <div style="margin-bottom: 1rem;">
                    <button class="btn" onclick="loadViewStats()">📊 刷新统计</button>
                    <button class="btn btn-warning" onclick="flushViewCount()">💾 刷新缓存到数据库</button>
                    <button class="btn btn-secondary" onclick="exportViewStats()">📥 导出统计</button>
                </div>
                <div id="viewStatsList">
                    <div class="loading"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 文章编辑模态框 -->
<div id="articleModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('articleModal')">&times;</span>
        <h2 id="articleModalTitle">新增文章</h2>
        <form id="articleForm">
            <div class="form-group">
                <label for="title">标题</label>
                <input type="text" id="title" name="title" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="author">作者</label>
                <input type="text" id="author" name="author" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="category">分类</label>
                <select id="category" name="category" class="form-control" required>
                    <option value="">请选择分类</option>
                </select>
            </div>
            <div class="form-group">
                <label for="summary">摘要</label>
                <textarea id="summary" name="summary" class="form-control" rows="3" required></textarea>
            </div>
            <div class="form-group">
                <label for="contentHtml">内容</label>
                <div class="editor-container">
                    <!-- 编辑器工具栏 -->
                    <div style="margin-bottom: 0.5rem;">
                        <button type="button" class="editor-toolbar-btn" onclick="insertTemplate('news')">📰 新闻模板</button>
                        <button type="button" class="editor-toolbar-btn" onclick="insertTemplate('interview')">🎤 访谈模板</button>
                        <button type="button" class="editor-toolbar-btn" onclick="insertTemplate('announcement')">📢 公告模板</button>
                        <button type="button" class="editor-toolbar-btn" onclick="clearContent()">🗑️ 清空内容</button>
                        <button type="button" class="editor-toolbar-btn" onclick="previewContent()">👁️ 预览</button>
                    </div>
                    <!-- Quill编辑器容器 -->
                    <div id="editor" style="height: 400px;"></div>
                </div>
                <!-- 隐藏的textarea用于表单提交 -->
                <textarea id="contentHtml" name="contentHtml" style="display: none;"></textarea>
            </div>
            <div class="form-group">
                <label for="tags">标签</label>
                <input type="text" id="tags" name="tags" class="form-control" placeholder="输入标签，用逗号分隔，或点击下方标签快速添加">
                <div id="availableTags" style="margin-top: 0.5rem;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                        <span style="font-size: 0.9rem; color: #718096;">点击添加标签：</span>
                        <button type="button" class="btn" style="padding: 0.25rem 0.5rem; font-size: 0.8rem;" onclick="quickAddTag()">+ 快速添加</button>
                    </div>
                    <div id="tagsContainer" style="display: flex; flex-wrap: wrap; gap: 0.5rem;">
                        <!-- 标签将在这里动态加载 -->
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="thumbnailUrl">缩略图URL</label>
                <input type="url" id="thumbnailUrl" name="thumbnailUrl" class="form-control">
            </div>
            <div class="form-group">
                <label for="source">来源</label>
                <input type="text" id="source" name="source" class="form-control">
            </div>
            <div class="form-group">
                <label>权重设置</label>
                <div class="weight-controls">
                    <div class="weight-item">
                        <input type="checkbox" id="isTop" name="isTop">
                        <label for="isTop">置顶</label>
                        <input type="number" id="topOrder" name="topOrder" placeholder="排序" style="width: 80px; margin-left: 10px;">
                    </div>
                    <div class="weight-item">
                        <input type="checkbox" id="isHot" name="isHot">
                        <label for="isHot">热门</label>
                        <input type="number" id="hotOrder" name="hotOrder" placeholder="排序" style="width: 80px; margin-left: 10px;">
                    </div>
                    <div class="weight-item">
                        <input type="checkbox" id="isRecommend" name="isRecommend">
                        <label for="isRecommend">推荐</label>
                        <input type="number" id="recommendOrder" name="recommendOrder" placeholder="排序" style="width: 80px; margin-left: 10px;">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="status">状态</label>
                <select id="status" name="status" class="form-control">
                    <option value="0">草稿</option>
                    <option value="1">发布</option>
                </select>
            </div>
            <div style="text-align: right;">
                <button type="button" class="btn btn-secondary" onclick="closeModal('articleModal')">取消</button>
                <button type="submit" class="btn">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 分类编辑模态框 -->
<div id="categoryModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('categoryModal')">&times;</span>
        <h2 id="categoryModalTitle">新增分类</h2>
        <form id="categoryForm">
            <div class="form-group">
                <label for="categoryName">分类名称</label>
                <input type="text" id="categoryName" name="name" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="categoryDisplayName">显示名称</label>
                <input type="text" id="categoryDisplayName" name="displayName" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="categoryDescription">描述</label>
                <textarea id="categoryDescription" name="description" class="form-control" rows="3"></textarea>
            </div>
            <div class="form-group">
                <label for="categoryIconUrl">图标URL</label>
                <input type="url" id="categoryIconUrl" name="iconUrl" class="form-control" placeholder="https://example.com/icon.png">
            </div>
            <div class="form-group">
                <label for="categorySortOrder">排序顺序</label>
                <input type="number" id="categorySortOrder" name="sortOrder" class="form-control" min="0" value="0">
            </div>
            <div class="form-group">
                <label>
                    <input type="checkbox" id="categoryIsActive" name="isActive" checked>
                    启用状态
                </label>
            </div>
            <div style="text-align: right;">
                <button type="button" class="btn btn-secondary" onclick="closeModal('categoryModal')">取消</button>
                <button type="submit" class="btn">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 标签编辑模态框 -->
<div id="tagModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('tagModal')">&times;</span>
        <h2 id="tagModalTitle">新增标签</h2>
        <form id="tagForm">
            <div class="form-group">
                <label for="tagName">标签名称</label>
                <input type="text" id="tagName" name="name" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="tagColor">标签颜色</label>
                <input type="color" id="tagColor" name="color" class="form-control" value="#667eea">
            </div>
            <div class="form-group">
                <label for="tagDescription">描述</label>
                <textarea id="tagDescription" name="description" class="form-control" rows="3"></textarea>
            </div>
            <div style="text-align: right;">
                <button type="button" class="btn btn-secondary" onclick="closeModal('tagModal')">取消</button>
                <button type="submit" class="btn">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 内容预览模态框 -->
<div id="previewModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('previewModal')">&times;</span>
        <h2>内容预览</h2>
        <div id="previewContent" style="padding: 1rem; border: 1px solid #e2e8f0; border-radius: 8px; background: #f8fafc; max-height: 500px; overflow-y: auto;">
        </div>
    </div>
</div>

<!-- Quill编辑器JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.7/quill.min.js"></script>

<script>
    // 全局变量
    let currentPage = 1;
    let pageSize = 10;
    let currentEditingId = null;
    let currentEditingTagId = null;
    let currentEditingCategoryId = null;
    let categories = [];
    let tags = [];
    let selectedTags = [];
    let viewCountCache = new Map();
    let quill = null; // Quill编辑器实例

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadCategories();
        loadArticles();
        loadTags();
        loadDashboardStats();

        // 绑定表单提交事件
        document.getElementById('articleForm').addEventListener('submit', handleArticleSubmit);
        document.getElementById('categoryForm').addEventListener('submit', handleCategorySubmit);
        document.getElementById('tagForm').addEventListener('submit', handleTagSubmit);

        // 监听标签输入框变化
        document.getElementById('tags').addEventListener('input', handleTagsInputChange);

        // 定时刷新浏览量统计
        setInterval(refreshViewCountCache, 30000); // 每30秒刷新一次
    });

    // 初始化Quill编辑器
    function initializeQuillEditor() {
        if (quill) {
            return; // 如果已经初始化过，直接返回
        }

        // Quill编辑器配置
        const toolbarOptions = [
            ['bold', 'italic', 'underline', 'strike'],        // 粗体、斜体、下划线、删除线
            ['blockquote', 'code-block'],                     // 引用、代码块

            [{ 'header': 1 }, { 'header': 2 }],               // 标题
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],     // 有序列表、无序列表
            [{ 'script': 'sub'}, { 'script': 'super' }],      // 上标、下标
            [{ 'indent': '-1'}, { 'indent': '+1' }],          // 缩进

            [{ 'direction': 'rtl' }],                         // 文本方向
            [{ 'size': ['small', false, 'large', 'huge'] }],  // 字体大小
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],        // 标题级别

            [{ 'color': [] }, { 'background': [] }],          // 字体颜色、背景色
            [{ 'font': [] }],                                 // 字体
            [{ 'align': [] }],                                // 对齐方式

            ['clean'],                                        // 清除格式
            ['link', 'image']                                 // 链接、图片
        ];

        quill = new Quill('#editor', {
            theme: 'snow',
            modules: {
                toolbar: {
                    container: toolbarOptions,
                    handlers: {
                        'image': imageHandler
                    }
                }
            },
            placeholder: '请输入文章内容...',
        });

        // 监听内容变化，同步到隐藏的textarea
        quill.on('text-change', function() {
            const htmlContent = quill.root.innerHTML;
            document.getElementById('contentHtml').value = htmlContent;
        });
    }

    // 自定义图片处理器
    function imageHandler() {
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.click();

        input.onchange = function() {
            const file = input.files[0];
            if (file) {
                // 这里可以实现图片上传逻辑
                // 现在先使用本地预览
                const reader = new FileReader();
                reader.onload = function(e) {
                    const range = quill.getSelection();
                    quill.insertEmbed(range.index, 'image', e.target.result);
                };
                reader.readAsDataURL(file);

                showAlert('success', '图片已插入（注意：当前为本地预览，实际使用需要配置图片上传服务）');
            }
        };
    }

    // 插入模板内容
    function insertTemplate(type) {
        if (!quill) return;

        let template = '';
        switch (type) {
            case 'news':
                template = `
                    <h2>新闻标题</h2>
                    <p><strong>【导语】</strong>简要概述新闻事件的主要内容...</p>

                    <h3>事件详情</h3>
                    <p>详细描述新闻事件的经过、背景和相关信息...</p>

                    <h3>各方反应</h3>
                    <p>相关人士、机构或专家的观点和反应...</p>

                    <h3>后续影响</h3>
                    <p>分析事件可能带来的影响和后续发展...</p>
                `;
                break;
            case 'interview':
                template = `
                    <h2>专访：[被访者姓名]</h2>
                    <p><strong>记者：</strong>请介绍一下...</p>
                    <p><strong>[被访者]：</strong>回答内容...</p>

                    <p><strong>记者：</strong>下一个问题...</p>
                    <p><strong>[被访者]：</strong>回答内容...</p>
                `;
                break;
            case 'announcement':
                template = `
                    <h2>重要公告</h2>
                    <p><strong>公告时间：</strong>YYYY年MM月DD日</p>
                    <p><strong>发布机构：</strong>机构名称</p>

                    <h3>公告内容</h3>
                    <p>具体公告内容...</p>

                    <h3>生效时间</h3>
                    <p>本公告自发布之日起生效。</p>
                `;
                break;
        }

        quill.clipboard.dangerouslyPasteHTML(template);
        showAlert('success', '模板已插入');
    }

    // 清空编辑器内容
    function clearContent() {
        if (quill && confirm('确定要清空所有内容吗？')) {
            quill.setContents([]);
            document.getElementById('contentHtml').value = '';
            showAlert('success', '内容已清空');
        }
    }

    // 预览内容
    function previewContent() {
        if (!quill) return;

        const htmlContent = quill.root.innerHTML;
        const previewElement = document.getElementById('previewContent');
        previewElement.innerHTML = htmlContent;
        document.getElementById('previewModal').style.display = 'block';
    }

    // 显示指定区域
    function showSection(sectionId) {
        document.querySelectorAll('.content-section').forEach(section => {
            section.classList.remove('active');
        });

        document.querySelectorAll('.nav-link').forEach(link => {
            link.classList.remove('active');
        });

        document.getElementById(sectionId).classList.add('active');
        event.target.classList.add('active');

        // 根据切换的区域加载对应数据
        if (sectionId === 'dashboard') {
            loadDashboardStats();
        } else if (sectionId === 'viewStats') {
            loadViewStats();
        }
    }

    // 显示新增文章模态框
    function showCreateArticleModal() {
        currentEditingId = null;
        document.getElementById('articleModalTitle').textContent = '新增文章';
        document.getElementById('articleForm').reset();
        document.getElementById('articleModal').style.display = 'block';
        initializeTagsState();
        addTagInputSuggestion();

        // 初始化编辑器
        setTimeout(() => {
            initializeQuillEditor();
            if (quill) {
                quill.setContents([]);
                document.getElementById('contentHtml').value = '';
            }
        }, 100);
    }

    // 编辑文章
    async function editArticle(id) {
        try {
            const response = await fetch(`/apis/admin/articles/${id}`);
            const result = await response.json();

            if (result.code === 200) {
                currentEditingId = id;
                document.getElementById('articleModalTitle').textContent = '编辑文章';

                const article = result.data;
                document.getElementById('title').value = article.title || '';
                document.getElementById('author').value = article.author || '';
                document.getElementById('category').value = article.category || '';
                document.getElementById('summary').value = article.summary || '';
                document.getElementById('tags').value = article.tags || '';
                document.getElementById('thumbnailUrl').value = article.thumbnailUrl || '';
                document.getElementById('source').value = article.source || '';
                document.getElementById('status').value = article.status || 0;

                // 设置权重
                document.getElementById('isTop').checked = article.isTop || false;
                document.getElementById('topOrder').value = article.topOrder || '';
                document.getElementById('isHot').checked = article.isHot || false;
                document.getElementById('hotOrder').value = article.hotOrder || '';
                document.getElementById('isRecommend').checked = article.isRecommend || false;
                document.getElementById('recommendOrder').value = article.recommendOrder || '';

                // 处理标签选择状态
                selectedTags = article.tags ? article.tags.split(',').map(tag => tag.trim()) : [];
                renderSelectableTags();
                addTagInputSuggestion();

                document.getElementById('articleModal').style.display = 'block';

                // 初始化编辑器并设置内容
                setTimeout(() => {
                    initializeQuillEditor();
                    if (quill && article.contentHtml) {
                        quill.clipboard.dangerouslyPasteHTML(article.contentHtml);
                        document.getElementById('contentHtml').value = article.contentHtml;
                    }
                }, 100);
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '加载文章失败: ' + error.message);
        }
    }

    // 处理文章表单提交
    async function handleArticleSubmit(e) {
        e.preventDefault();

        // 确保编辑器内容同步到隐藏字段
        if (quill) {
            const htmlContent = quill.root.innerHTML;
            document.getElementById('contentHtml').value = htmlContent;
        }

        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData);

        // 确保标签数据正确获取
        const tagsInput = document.getElementById('tags');
        data.tags = tagsInput.value.trim();

        // 处理权重数据
        data.isTop = document.getElementById('isTop').checked;
        data.isHot = document.getElementById('isHot').checked;
        data.isRecommend = document.getElementById('isRecommend').checked;
        data.topOrder = data.topOrder ? parseInt(data.topOrder) : null;
        data.hotOrder = data.hotOrder ? parseInt(data.hotOrder) : null;
        data.recommendOrder = data.recommendOrder ? parseInt(data.recommendOrder) : null;
        data.status = parseInt(data.status);

        try {
            const url = currentEditingId ? `/apis/admin/articles/${currentEditingId}` : '/apis/admin/articles';
            const method = currentEditingId ? 'PUT' : 'POST';

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                closeModal('articleModal');
                loadArticles();
                selectedTags = [];
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '操作失败: ' + error.message);
        }
    }

    // 关闭模态框
    function closeModal(modalId) {
        document.getElementById(modalId).style.display = 'none';

        if (modalId === 'articleModal') {
            selectedTags = [];
            const tagsInput = document.getElementById('tags');
            if (tagsInput) {
                tagsInput.value = '';
            }

            // 清理编辑器
            if (quill) {
                quill.setContents([]);
                document.getElementById('contentHtml').value = '';
            }
        }
    }

    // 以下是原有的其他函数（保持不变）...

    // 加载仪表盘统计数据
    async function loadDashboardStats() {
        try {
            // 加载基础统计
            const [articlesResponse, categoriesResponse, tagsResponse] = await Promise.all([
                fetch('/apis/admin/articles?page=1&size=1'),
                fetch('/apis/admin/categories'),
                fetch('/apis/admin/tags')
            ]);

            const articlesResult = await articlesResponse.json();
            const categoriesResult = await categoriesResponse.json();
            const tagsResult = await tagsResponse.json();

            if (articlesResult.code === 200) {
                document.getElementById('totalArticles').textContent = articlesResult.data.total || 0;

                // 计算已发布文章数
                const publishedCount = articlesResult.data.records ?
                    articlesResult.data.records.filter(a => a.status === 1).length : 0;
                document.getElementById('publishedArticles').textContent = publishedCount;

                // 计算总浏览量
                const totalViews = articlesResult.data.records ?
                    articlesResult.data.records.reduce((sum, article) => sum + (article.viewCount || 0), 0) : 0;
                document.getElementById('totalViews').textContent = formatNumber(totalViews);
            }

            if (categoriesResult.code === 200) {
                document.getElementById('totalCategories').textContent = categoriesResult.data.length || 0;
            }

            if (tagsResult.code === 200) {
                document.getElementById('totalTags').textContent = tagsResult.data.length || 0;
            }

        } catch (error) {
            console.error('加载统计数据失败:', error);
        }
    }

    // 格式化数字显示
    function formatNumber(num) {
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
    }

    // 刷新统计数据
    function refreshStats() {
        loadDashboardStats();
        showAlert('success', '统计数据已刷新');
    }

    // 刷新浏览量缓存
    async function flushViewCount() {
        try {
            const response = await fetch('/apis/view/flush', {
                method: 'POST'
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                loadDashboardStats();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '刷新缓存失败: ' + error.message);
        }
    }

    // 刷新浏览量缓存（定时任务）
    async function refreshViewCountCache() {
        try {
            // 获取当前显示的文章ID
            const articles = document.querySelectorAll('[data-article-id]');
            if (articles.length === 0) return;

            const articleIds = Array.from(articles).map(el => el.getAttribute('data-article-id'));

            const response = await fetch('/apis/view/articles/batch-count', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ articleIds })
            });

            const result = await response.json();

            if (result.code === 200 && result.data) {
                // 更新缓存
                Object.entries(result.data).forEach(([articleId, count]) => {
                    viewCountCache.set(articleId, count);
                    // 更新UI显示
                    const element = document.querySelector(`[data-article-id="${articleId}"] .view-count-display`);
                    if (element) {
                        element.textContent = formatNumber(count);
                    }
                });
            }
        } catch (error) {
            console.error('刷新浏览量缓存失败:', error);
        }
    }

    // 刷新文章浏览量
    async function refreshArticleViews() {
        await refreshViewCountCache();
        showAlert('success', '文章浏览量已刷新');
    }

    // 加载浏览统计
    async function loadViewStats() {
        const listContainer = document.getElementById('viewStatsList');
        listContainer.innerHTML = '<div class="loading"></div>';

        try {
            const response = await fetch('/apis/admin/articles?page=1&size=50');
            const result = await response.json();

            if (result.code === 200 && result.data.records) {
                const articles = result.data.records;

                // 按浏览量排序
                articles.sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0));

                let html = '<table class="table">';
                html += '<thead><tr><th>文章标题</th><th>分类</th><th>浏览量</th><th>发布时间</th><th>状态</th></tr></thead>';
                html += '<tbody>';

                articles.forEach(article => {
                    const statusBadge = article.status === 1 ?
                        '<span class="status-badge status-published">已发布</span>' :
                        '<span class="status-badge status-draft">草稿</span>';

                    html += `
                        <tr data-article-id="${article.id}">
                            <td style="max-width: 300px; word-wrap: break-word;">${article.title}</td>
                            <td>${article.category}</td>
                            <td><span class="view-count-display">${formatNumber(article.viewCount || 0)}</span></td>
                            <td>${formatDate(article.createTime)}</td>
                            <td>${statusBadge}</td>
                        </tr>
                    `;
                });

                html += '</tbody></table>';
                listContainer.innerHTML = html;

                // 刷新浏览量
                setTimeout(refreshViewCountCache, 1000);
            }
        } catch (error) {
            listContainer.innerHTML = '<p style="text-align: center; color: #e74c3c;">加载失败: ' + error.message + '</p>';
        }
    }

    // 导出浏览统计
    function exportViewStats() {
        // 简单的CSV导出
        const table = document.querySelector('#viewStatsList table');
        if (!table) {
            showAlert('error', '没有可导出的数据');
            return;
        }

        let csv = '文章标题,分类,浏览量,发布时间,状态\n';

        const rows = table.querySelectorAll('tbody tr');
        rows.forEach(row => {
            const cells = row.querySelectorAll('td');
            const rowData = Array.from(cells).map(cell => {
                return '"' + cell.textContent.replace(/"/g, '""') + '"';
            }).join(',');
            csv += rowData + '\n';
        });

        // 创建下载链接
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = '浏览统计_' + new Date().toISOString().split('T')[0] + '.csv';
        link.click();

        showAlert('success', '统计数据已导出');
    }

    // 加载分类列表
    async function loadCategories() {
        try {
            const response = await fetch('/apis/admin/categories');
            const result = await response.json();

            if (result.code === 200) {
                categories = result.data;
                renderCategoriesList(result.data);
                updateCategoryOptions();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '加载分类失败: ' + error.message);
        }
    }

    // 渲染分类列表
    function renderCategoriesList(categoriesData) {
        const listContainer = document.getElementById('categoriesList');

        if (!categoriesData || categoriesData.length === 0) {
            listContainer.innerHTML = '<p style="text-align: center; color: #718096;">暂无分类</p>';
            return;
        }

        let html = '<table class="table"><thead><tr><th>显示名称</th><th>名称</th><th>描述</th><th>图标</th><th>排序</th><th>状态</th><th>操作</th></tr></thead><tbody>';

        categoriesData.forEach(category => {
            const statusBadge = category.isActive ?
                '<span class="status-badge status-published">启用</span>' :
                '<span class="status-badge status-draft">禁用</span>';

            const icon = category.iconUrl ?
                `<img src="${category.iconUrl}" alt="icon" style="width: 24px; height: 24px; border-radius: 4px;">` :
                '<span style="color: #718096;">-</span>';

            html += `
                <tr>
                    <td style="font-weight: 500;">${category.displayName}</td>
                    <td>${category.name}</td>
                    <td style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${category.description || '-'}</td>
                    <td>${icon}</td>
                    <td>${category.sortOrder}</td>
                    <td>${statusBadge}</td>
                    <td>
                        <button class="btn" style="padding: 0.25rem 0.5rem; margin-right: 0.25rem;" onclick="editCategory(${category.id})">编辑</button>
                        <button class="btn ${category.isActive ? 'btn-secondary' : 'btn-success'}" style="padding: 0.25rem 0.5rem; margin-right: 0.25rem;" onclick="toggleCategoryStatus(${category.id})">
                            ${category.isActive ? '禁用' : '启用'}
                        </button>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem;" onclick="deleteCategory(${category.id})">删除</button>
                    </td>
                </tr>
            `;
        });

        html += '</tbody></table>';
        listContainer.innerHTML = html;
    }

    // 更新分类选项
    function updateCategoryOptions() {
        const categoryFilter = document.getElementById('categoryFilter');
        const categorySelect = document.getElementById('category');

        // 清空现有选项
        categoryFilter.innerHTML = '<option value="">全部分类</option>';
        categorySelect.innerHTML = '<option value="">请选择分类</option>';

        // 添加分类选项
        categories.forEach(category => {
            if (category.isActive) {
                const option1 = new Option(category.displayName, category.name);
                const option2 = new Option(category.displayName, category.name);
                categoryFilter.appendChild(option1);
                categorySelect.appendChild(option2);
            }
        });
    }

    // 显示新增分类模态框
    function showCreateCategoryModal() {
        currentEditingCategoryId = null;
        document.getElementById('categoryModalTitle').textContent = '新增分类';
        document.getElementById('categoryForm').reset();
        document.getElementById('categoryIsActive').checked = true;
        document.getElementById('categoryModal').style.display = 'block';
    }

    // 编辑分类
    async function editCategory(id) {
        try {
            const response = await fetch(`/apis/admin/categories/${id}`);
            const result = await response.json();

            if (result.code === 200) {
                currentEditingCategoryId = id;
                document.getElementById('categoryModalTitle').textContent = '编辑分类';

                const category = result.data;
                document.getElementById('categoryName').value = category.name || '';
                document.getElementById('categoryDisplayName').value = category.displayName || '';
                document.getElementById('categoryDescription').value = category.description || '';
                document.getElementById('categoryIconUrl').value = category.iconUrl || '';
                document.getElementById('categorySortOrder').value = category.sortOrder || 0;
                document.getElementById('categoryIsActive').checked = category.isActive;

                document.getElementById('categoryModal').style.display = 'block';
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '加载分类失败: ' + error.message);
        }
    }

    // 处理分类表单提交
    async function handleCategorySubmit(e) {
        e.preventDefault();

        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData);

        // 处理布尔值
        data.isActive = document.getElementById('categoryIsActive').checked;
        data.sortOrder = parseInt(data.sortOrder) || 0;

        try {
            const url = currentEditingCategoryId ? `/apis/admin/categories/${currentEditingCategoryId}` : '/apis/admin/categories';
            const method = currentEditingCategoryId ? 'PUT' : 'POST';

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                closeModal('categoryModal');
                loadCategories();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '操作失败: ' + error.message);
        }
    }

    // 切换分类状态
    async function toggleCategoryStatus(id) {
        try {
            const response = await fetch(`/apis/admin/categories/${id}/toggle`, {
                method: 'POST'
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                loadCategories();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '操作失败: ' + error.message);
        }
    }

    // 删除分类
    async function deleteCategory(id) {
        if (!confirm('确定要删除这个分类吗？删除后该分类下的文章将无法正常显示。')) {
            return;
        }

        try {
            const response = await fetch(`/apis/admin/categories/${id}`, {
                method: 'DELETE'
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                loadCategories();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '删除失败: ' + error.message);
        }
    }

    // 加载文章列表
    async function loadArticles() {
        try {
            const keyword = document.getElementById('searchKeyword').value;
            const category = document.getElementById('categoryFilter').value;
            const status = document.getElementById('statusFilter').value;

            const params = new URLSearchParams({
                page: currentPage,
                size: pageSize
            });

            if (keyword) params.append('keyword', keyword);
            if (category) params.append('category', category);
            if (status) params.append('status', status);

            const response = await fetch(`/apis/admin/articles?${params}`);
            const result = await response.json();

            if (result.code === 200) {
                renderArticlesList(result.data);
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '加载文章失败: ' + error.message);
        }
    }

    // 渲染文章列表
    function renderArticlesList(pageData) {
        const listContainer = document.getElementById('articlesList');

        if (!pageData.records || pageData.records.length === 0) {
            listContainer.innerHTML = '<p style="text-align: center; color: #718096;">暂无文章</p>';
            return;
        }

        let html = '<table class="table"><thead><tr><th>标题</th><th>作者</th><th>分类</th><th>状态</th><th>浏览量</th><th>创建时间</th><th>操作</th></tr></thead><tbody>';

        pageData.records.forEach(article => {
            const statusBadge = article.status === 1 ?
                '<span class="status-badge status-published">已发布</span>' :
                '<span class="status-badge status-draft">草稿</span>';

            const tags = article.tags ? article.tags.split(',').map(tag =>
                `<span class="tag">${tag.trim()}</span>`
            ).join('') : '';

            html += `
                <tr data-article-id="${article.id}">
                    <td>
                        <div style="font-weight: 500;">${article.title}</div>
                        <div style="font-size: 0.8rem; color: #718096; margin-top: 0.25rem;">${tags}</div>
                    </td>
                    <td>${article.author}</td>
                    <td>${article.category}</td>
                    <td>${statusBadge}</td>
                    <td><span class="view-count-display">${formatNumber(article.viewCount || 0)}</span></td>
                    <td>${formatDate(article.createTime)}</td>
                    <td>
                        <button class="btn" style="padding: 0.25rem 0.5rem; margin-right: 0.25rem;" onclick="editArticle('${article.id}')">编辑</button>
                        <button class="btn ${article.status === 1 ? 'btn-secondary' : 'btn-success'}" style="padding: 0.25rem 0.5rem; margin-right: 0.25rem;" onclick="toggleArticleStatus('${article.id}', ${article.status})">
                            ${article.status === 1 ? '撤回' : '发布'}
                        </button>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem;" onclick="deleteArticle('${article.id}')">删除</button>
                    </td>
                </tr>
            `;
        });

        html += '</tbody></table>';
        html += renderPagination(pageData);
        listContainer.innerHTML = html;

        // 刷新浏览量
        setTimeout(refreshViewCountCache, 1000);
    }

    // 渲染分页
    function renderPagination(pageData) {
        const totalPages = pageData.pages;
        const current = pageData.current;

        let html = '<div class="pagination">';
        html += `<button ${current <= 1 ? 'disabled' : ''} onclick="changePage(${current - 1})">上一页</button>`;

        for (let i = Math.max(1, current - 2); i <= Math.min(totalPages, current + 2); i++) {
            html += `<button class="${i === current ? 'active' : ''}" onclick="changePage(${i})">${i}</button>`;
        }

        html += `<button ${current >= totalPages ? 'disabled' : ''} onclick="changePage(${current + 1})">下一页</button>`;
        html += '</div>';
        return html;
    }

    // 切换页面
    function changePage(page) {
        currentPage = page;
        loadArticles();
    }

    // 搜索文章
    function searchArticles() {
        currentPage = 1;
        loadArticles();
    }

    // 筛选文章
    function filterArticles() {
        currentPage = 1;
        loadArticles();
    }

    // 初始化标签状态
    function initializeTagsState() {
        selectedTags = [];
        const tagsInput = document.getElementById('tags');
        if (tagsInput) {
            tagsInput.value = '';
        }
        renderSelectableTags();
    }

    // 切换文章状态
    async function toggleArticleStatus(id, currentStatus) {
        try {
            const action = currentStatus === 1 ? 'withdraw' : 'publish';
            const response = await fetch(`/apis/admin/articles/${id}/${action}`, {
                method: 'POST'
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                loadArticles();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '操作失败: ' + error.message);
        }
    }

    // 删除文章
    async function deleteArticle(id) {
        if (!confirm('确定要删除这篇文章吗？此操作无法撤销。')) {
            return;
        }

        try {
            const response = await fetch(`/apis/admin/articles/${id}`, {
                method: 'DELETE'
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                loadArticles();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '删除失败: ' + error.message);
        }
    }

    // 加载标签列表
    async function loadTags() {
        try {
            const response = await fetch('/apis/admin/tags');
            const result = await response.json();

            if (result.code === 200) {
                tags = result.data;
                renderTagsList(result.data);

                const articleModal = document.getElementById('articleModal');
                if (articleModal && articleModal.style.display === 'block') {
                    renderSelectableTags();
                    addTagInputSuggestion();
                }

                return result.data;
            } else {
                showAlert('error', result.message);
                return [];
            }
        } catch (error) {
            showAlert('error', '加载标签失败: ' + error.message);
            return [];
        }
    }

    // 渲染标签列表
    function renderTagsList(tags) {
        const listContainer = document.getElementById('tagsList');

        if (!tags || tags.length === 0) {
            listContainer.innerHTML = '<p style="text-align: center; color: #718096;">暂无标签</p>';
            return;
        }

        let html = '<table class="table"><thead><tr><th>名称</th><th>颜色</th><th>描述</th><th>使用次数</th><th>操作</th></tr></thead><tbody>';

        tags.forEach(tag => {
            html += `
                <tr>
                    <td><span class="tag" style="background-color: ${tag.color}20; color: ${tag.color}">${tag.name}</span></td>
                    <td><div style="width: 20px; height: 20px; background-color: ${tag.color}; border-radius: 4px;"></div></td>
                    <td>${tag.description || '-'}</td>
                    <td>${tag.usageCount || 0}</td>
                    <td>
                        <button class="btn" style="padding: 0.25rem 0.5rem; margin-right: 0.25rem;" onclick="editTag(${tag.id})">编辑</button>
                        <button class="btn btn-danger" style="padding: 0.25rem 0.5rem;" onclick="deleteTag(${tag.id})">删除</button>
                    </td>
                </tr>
            `;
        });

        html += '</tbody></table>';
        listContainer.innerHTML = html;
    }

    // 显示新增标签模态框
    function showCreateTagModal() {
        currentEditingTagId = null;
        document.getElementById('tagModalTitle').textContent = '新增标签';
        document.getElementById('tagForm').reset();
        document.getElementById('tagColor').value = '#667eea';
        document.getElementById('tagModal').style.display = 'block';
    }

    // 编辑标签
    function editTag(id) {
        currentEditingTagId = id;
        document.getElementById('tagModalTitle').textContent = '编辑标签';
        document.getElementById('tagModal').style.display = 'block';
    }

    // 处理标签表单提交
    async function handleTagSubmit(e) {
        e.preventDefault();

        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData);

        try {
            const url = currentEditingTagId ? `/apis/admin/tags/${currentEditingTagId}` : '/apis/admin/tags';
            const method = currentEditingTagId ? 'PUT' : 'POST';

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                closeModal('tagModal');
                loadTags();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '操作失败: ' + error.message);
        }
    }

    // 删除标签
    async function deleteTag(id) {
        if (!confirm('确定要删除这个标签吗？')) {
            return;
        }

        try {
            const response = await fetch(`/apis/admin/tags/${id}`, {
                method: 'DELETE'
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                loadTags();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '删除失败: ' + error.message);
        }
    }

    // 快速添加标签
    function quickAddTag() {
        const tagName = prompt('请输入新标签名称：');
        if (!tagName || !tagName.trim()) {
            return;
        }

        const trimmedName = tagName.trim();
        const existingTag = tags.find(tag => tag.name === trimmedName);

        if (existingTag) {
            if (!selectedTags.includes(trimmedName)) {
                selectedTags.push(trimmedName);
                updateTagsInput();
                renderSelectableTags();
            }
            showAlert('success', '标签已添加到文章中');
            return;
        }

        const newTag = {
            name: trimmedName,
            color: '#667eea',
            description: '快速创建的标签'
        };

        fetch('/apis/admin/tags', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(newTag)
        })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    showAlert('success', '新标签创建成功');
                    loadTags().then(() => {
                        if (!selectedTags.includes(trimmedName)) {
                            selectedTags.push(trimmedName);
                            updateTagsInput();
                            renderSelectableTags();
                            addTagInputSuggestion();
                        }
                    });
                } else {
                    showAlert('error', result.message);
                }
            })
            .catch(error => {
                showAlert('error', '创建标签失败: ' + error.message);
            });
    }

    // 渲染可选择的标签
    function renderSelectableTags() {
        const container = document.getElementById('tagsContainer');

        if (!tags || tags.length === 0) {
            container.innerHTML = '<span style="color: #718096; font-size: 0.8rem;">暂无标签</span>';
            return;
        }

        container.innerHTML = '';

        tags.forEach(tag => {
            const isSelected = selectedTags.includes(tag.name);
            const tagElement = document.createElement('span');
            tagElement.className = `tag-selectable ${isSelected ? 'selected' : ''}`;
            tagElement.style.backgroundColor = tag.color + '20';
            tagElement.style.color = tag.color;
            if (isSelected) {
                tagElement.style.borderColor = tag.color;
            }
            tagElement.textContent = tag.name;
            tagElement.title = tag.description || tag.name;

            tagElement.addEventListener('click', function() {
                toggleTag(tag.name);
            });

            container.appendChild(tagElement);
        });
    }

    // 切换标签选择状态
    function toggleTag(tagName) {
        const index = selectedTags.indexOf(tagName);
        if (index > -1) {
            selectedTags.splice(index, 1);
        } else {
            selectedTags.push(tagName);
        }

        updateTagsInput();
        renderSelectableTags();
    }

    // 更新标签输入框
    function updateTagsInput() {
        const tagsInput = document.getElementById('tags');
        const tagsValue = selectedTags.join(', ');
        tagsInput.value = tagsValue;

        const event = new Event('input', { bubbles: true });
        tagsInput.dispatchEvent(event);
    }

    // 监听标签输入框变化
    function handleTagsInputChange() {
        const tagsInput = document.getElementById('tags');
        const inputValue = tagsInput.value;

        if (inputValue.trim()) {
            selectedTags = inputValue.split(',').map(tag => tag.trim()).filter(tag => tag);
        } else {
            selectedTags = [];
        }

        renderSelectableTags();
    }

    // 添加输入提示功能
    function addTagInputSuggestion() {
        const tagsInput = document.getElementById('tags');

        if (!tags || tags.length === 0) {
            return;
        }

        let dataList = document.getElementById('tagSuggestions');
        if (!dataList) {
            dataList = document.createElement('datalist');
            dataList.id = 'tagSuggestions';
            tagsInput.parentNode.appendChild(dataList);
        }

        dataList.innerHTML = '';
        tags.forEach(tag => {
            const option = document.createElement('option');
            option.value = tag.name;
            option.textContent = tag.name;
            dataList.appendChild(option);
        });

        tagsInput.setAttribute('list', 'tagSuggestions');
    }

    // 清理旧新闻
    async function clearOldNews() {
        if (!confirm('确定要清理30天前的旧新闻吗？此操作无法撤销。')) {
            return;
        }

        try {
            const response = await fetch('/apis/admin/clear-old', {
                method: 'POST'
            });

            const result = await response.json();

            if (result.code === 200) {
                showAlert('success', result.message);
                loadDashboardStats();
            } else {
                showAlert('error', result.message);
            }
        } catch (error) {
            showAlert('error', '操作失败: ' + error.message);
        }
    }

    // 显示提示消息
    function showAlert(type, message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type}`;
        alertDiv.textContent = message;
        alertDiv.style.position = 'fixed';
        alertDiv.style.top = '20px';
        alertDiv.style.right = '20px';
        alertDiv.style.zIndex = '9999';
        alertDiv.style.minWidth = '300px';

        document.body.appendChild(alertDiv);

        setTimeout(() => {
            alertDiv.remove();
        }, 3000);
    }

    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        if (event.target.classList.contains('modal')) {
            event.target.style.display = 'none';
        }
    }
</script>
</body>
</html>